import json
from functools import wraps
from django.http import JsonResponse
from django_redis import get_redis_connection


def custom_cache_decorator(timeout=2*60*60):
    cache = get_redis_connection('cache')

    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            user_id = request.COOKIES.get('user_id')
            class_name = view_func.func.__self__.__class__.__name__
            def_name = view_func.func.__name__
            cache_key = f"{class_name}_{def_name}_{user_id}"
            cached_data = cache.get(cache_key)
            try:
                verify = json.loads(cached_data)
                if verify.get('message') == 'OK':
                    return JsonResponse(json.loads(cached_data))
                raise ValueError
            except:
                response = view_func(request, *args, **kwargs)
                response_data = json.loads(response.content)
                cache.set(cache_key, json.dumps(response_data), timeout)
                return response
            # if cached_data:
            #     return JsonResponse(json.loads(cached_data))
            # else:
            #     response = view_func(request, *args, **kwargs)
            #     response_data = json.loads(response.content)
            #     cache.set(cache_key, json.dumps(response_data), timeout)
            #     return response

        return wrapper

    return decorator



# 公用缓存
def public_cache_decorator(timeout: int = 3 * 60 * 60):
    """
        用于缓存视图函数响应的装饰器.
        timeout （int）：缓存的超时时间（以秒为单位）
        """
    cache = get_redis_connection('cache')

    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            channel_id = request.GET.get('channel_id')
            if channel_id:
                const = channel_id
            else:
                raise ValueError
            class_name = view_func.func.__self__.__class__.__name__
            def_name = view_func.func.__name__
            cache_key = f"{class_name}_{def_name}_{const}"
            cached_data = cache.get(cache_key)
            try:
                verify = json.loads(cached_data)
                if verify.get('message') == 'OK' and len(verify.get('data')) > 1:
                    return JsonResponse(json.loads(cached_data))
                raise ValueError
            except Exception as e:
                print(e)
                response = view_func(request, *args, **kwargs)
                response_data = json.loads(response.content)
                cache.set(cache_key, json.dumps(response_data), timeout)
                return response

        return wrapper

    return decorator